//
//  BlogController.swift
//  App
//
//  Created by yuany on 2020/1/6.
//

import Foundation
import Vapor

final class BlogController: RouteCollection {
    private lazy var rootPath: String = DirectoryConfiguration.detect().publicDirectory + "Blogs/"
    
    func boot(routes: RoutesBuilder) throws {
        let blog = routes.grouped(Api.V1.Blog.group)
        
        blog.get(Api.V1.Blog.list.asPath, use: publiBlogs)
        blog.get(Api.V1.Blog.detail.asPath, use: blogDetail)
    }
}

extension BlogController {
    func publiBlogs(_ req: Request) throws -> EventLoopFuture<Response> {
        var path = rootPath
        if let subPath = try? req.query.get(String.self, at: "folder") {
            path += subPath
        }
        
        return try req.toJson(with: blogs(in: path))
    }
    
    func blogDetail(_ req: Request) throws -> EventLoopFuture<Response> {
        let path = rootPath + (try req.query.get(String.self, at: "relative_path"))
        return try req.toJson(with: String(contentsOfFile: path, encoding: .utf8))
    }
    
    private func blogs(in path: String) throws -> [Blog] {
        let folder = try YYFile.Folder(path: path)
        let files = folder.files.map {
             Blog(name: $0.name, isFolder: $0.kind == .folder, relativePath: $0.path.removingPrefix(rootPath))
        }
        
        let folders = folder.subfolders.map {
            Blog(name: $0.name, isFolder: $0.kind == .folder, relativePath: $0.path.removingPrefix(rootPath))
        }
        
        return files + folders
    }
}
